<template>
  <div class="employee-container" v-auth="'sys:user:list'">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">员工姓名：</div>

      <el-input
        clearable
        placeholder="请输入内容"
        class="search-main"
        v-model="params.name"
        @close="doSearch"
      />
      <el-button type="primary" @click="doSearch" v-auth-btn="'sys:user:list'">查询</el-button>
    </div>

    <div class="create-container">
      <el-button type="primary" @click="addEmployee" v-auth-btn="'sys:user:add_edit'">添加员工</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="employeeList">
        <el-table-column type="index" label="序号" />
        <el-table-column label="员工姓名" width="180" prop="name" />
        <el-table-column label="登录账号" prop="userName" />
        <el-table-column label="联系方式" prop="phonenumber" />
        <el-table-column label="角色" prop="roleName" />
        <el-table-column label="状态" width="150">
          <template #default="scope">
            <el-tag :type="formatInfoType(scope.row.status)">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="添加时间" prop="createTime" />
        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            <el-button size="mini" type="text" @click="editData(scope.row.id)" v-auth-btn="'sys:user:add_edit'">编辑</el-button>
            <el-button size="mini" type="text" @click="DeleteData(scope.row.id)" v-auth-btn="'sys:user:remove'">删除</el-button>

            <el-button
              size="mini"
              type="text"
              @click="resetPassword(scope.row.id)"
              v-auth-btn="'sys:user:resetPwd'"
            >重置密码</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="480px"
        @close="close"
      >
        <div class="form-container">
          <el-form
            :model="formData"
            :rules="rules"
            ref="formData"
            label-width="100px"
          >
            <el-form-item label="员工姓名" prop="name">
              <el-input v-model="formData.name" />
            </el-form-item>

            <el-form-item label="登录账号" prop="userName">
              <el-input v-model="formData.userName" />
            </el-form-item>

            <el-form-item label="联系方式" prop="phonenumber">
              <el-input v-model="formData.phonenumber" />
            </el-form-item>

            <el-form-item label="分配角色" prop="roleId">
              <el-select v-model="formData.roleId" placeholder="请选择角色">
                <el-option
                  v-for="item in roleList"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="员工状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio :label="0">禁用</el-radio>
                <el-radio :label="1">启用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <el-button type="danger" @click="close">取 消</el-button>
          <el-button type="primary" @click="confirmsubmit">确 定</el-button>
        </template>
      </el-dialog>
    </div>

    <div class="page-container">
      <el-pagination
        :current-page="employeeList.page"
        :page-size="employeeList.pageSize"
        :total="total"
        :page-sizes="pageSizes"
        background
        layout="total, sizes,prev, pager, next"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script>
import {
  getEmployeeList,
  getEmployeeDetail,
  getroleList,
  createEmployeeAPI,
  updateEmployeeAPI,
  deleteEmployeeAPI,
  resetPassword
} from "@/api/employee";
export default {
  name: "Employee",
  data() {
    const validatePhone = (rule, value, callback) => {
      if (/^1[3-9]\d{9}$/.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正常的手机号"));
      }
    };
    return {
      total: 0,
      title: "",
      dialogVisible: false,
      params: {
        page: 1,
        pageSize: 10,
        name: "",
      },
      pageSizes: [2, 5, 10, 20],
      employeeList: [],
      roleList: [],
      formData: {
        name: "",
        phonenumber: "",
        roleId: "",
        status: 1,
        userName: "",
      },
      rules: {
        name: [{ required: true, message: "请输入员工姓名", trigger: "blur" }],
        userName: [
          { required: true, message: "请输入登录账号", trigger: "blur" },
        ],
        phonenumber: [
          { required: true, message: "请输入联系方式", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" },
        ],
        roleId: [{ required: true, message: "请分配角色", trigger: "blur" }],
        status: [
          { required: true, message: "请选择员工状态", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getEmployeeList();
  },
  methods: {
    async getEmployeeList() {
      let res = await getEmployeeList(this.params);
      this.total = res.data.total;
      this.employeeList = res.data.rows;
    },
    handleCurrentChange(currentPage) {
      this.params.page = currentPage;
      this.getEmployeeList();
    },
    handleSizeChange(size) {
      this.params.pageSize = size;
      this.getEmployeeList();
    },
    doSearch() {
      this.getEmployeeList();
    },
    getroleList() {
      getroleList().then((res) => {
        this.roleList = res.data;
      });
    },
    addEmployee() {
      this.formData = {}
      this.title = "添加员工";
      this.dialogVisible = true;
      this.getroleList();
    },

    async editData(id) {
      this.title = "编辑员工";
      this.dialogVisible = true;
      this.getroleList();
      let res = await getEmployeeDetail(id);
      console.log(res.data);
      this.formData = res.data;
    },
    close() {
      this.dialogVisible = false;
      this.$refs.formData.resetFields();
    },
    confirmsubmit() {
      this.$refs.formData.validate(async (valid) => {
        if (!valid) return;
        if (this.title === "编辑员工") {
          delete this.formData.createTime;
          await updateEmployeeAPI(this.formData);
          this.$message.success("编辑成功");
        } else {
          try{
            await createEmployeeAPI(this.formData)
            this.$message.success("添加成功")
          }catch(err){
            this.$message.error('账户已存在,请重新输入')
          }
        }
        this.getEmployeeList();
        this.close();
      });
    },
    formatInfoType(status) {
      const MAP = {
        0: "danger",
        1: "success",
      };
      // return 格式化之后的中文显示
      return MAP[status];
    },
    formatStatus(type) {
      //中括号取值法
      const TYPEMAP = {
        0: "禁用",
        1: "启用",
      };
      return TYPEMAP[type];
    },
    DeleteData(id){
     this.$confirm("删除员工后将不可登录，确认删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await deleteEmployeeAPI(id)
          this.$message.success("删除成功")
          this.getEmployeeList()
        })
        .catch((error) => 
        {
          this.$message.info("已取消操作");
        });
    },
    resetPassword(id)
    {
      this.$confirm("确定要重置密码吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(  async () => {
        let res = await resetPassword({ id })
        this.$message.success(res.msg)
      })
       .catch((e) => 
        {
          this.$message.info(e.msg);
        });
    }
  },
  watch: {
    "params.name"(newVal, oldVal) {
      if (!newVal) {
        this.getEmployeeList();
      }
    },
    deep: true,
  },
};
</script>

<style lang="scss" scoped>
.employee-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container {
  margin: 10px 0px;
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
.form-container {
  padding: 0px 80px;
}
</style>
